import { createRouter, createWebHistory } from "vue-router";
import routerA from "./router";
import routerB from "./work";
import routerC from "./mobile";
import { useAppStore } from "@/store/modules/user";
import { createDeviceDetector } from "next-vue-device-detector";
const routes = [...routerA, ...routerB, ...routerC]; //可导入多个 [...routerA,...routerB]
import Cookies from "js-cookie";
const device = createDeviceDetector();
const router = createRouter({
  history: createWebHistory(),
  routes,
});
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪一个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行 next('/login') 跳转
  //解决页面刷新store会重置问题
  const token = Cookies.get("token");
  const userInfo = Cookies.get("userInfo");
  console.log("device==", device.mobile);

  if (device.mobile && !to.path.includes("/m/")) {
    const path = "/m" + to.path;
    return next(path);
  } else if (!device.mobile && to.path.includes("/m")) {
    const path = to.path.replace("/m", "");
    return next(path);
  } else if (token) {
    useAppStore().setToken(token);
    try {
      // 放行
      if (userInfo) {
        const user = JSON.parse(userInfo);
        useAppStore().setUserInfo(user);
      }
      if (to.path !== "/login" && to.path !== "/m/login") {
        return next();
      } else {
        return next("/");
      }
    } catch (error) {
      return next("/login");
    }
  } else {
    if (to.path === "/login" || to.path === "/m/login") {
      return next();
    } else {
      return next("/login");
    }
  }
});
export default router;
